﻿using System;
using System.Diagnostics;

namespace K9Nano.Updater.Utils;

internal static class ProcessUtils
{
    public static int Run(string command, string? args, Action<string?>? outputAction)
    {
        var process = Process.Start(new ProcessStartInfo
        {
            FileName = command,
            Arguments = args ?? string.Empty,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true,
            StandardOutputEncoding = System.Text.Encoding.UTF8,
            StandardErrorEncoding = System.Text.Encoding.UTF8,
        });

        if (process is null)
        {
            throw new UpdaterException($"无法启动进程: {command} {args}");
        }

        if (outputAction != null)
        {
            process.OutputDataReceived += (sender, eventArgs) =>
            {
                outputAction.Invoke(eventArgs?.Data);
            };

            process.BeginOutputReadLine();
        }

        process.WaitForExit();

        if (outputAction != null && process.ExitCode != 0)
        {
            var error = process.StandardError.ReadToEnd();
            outputAction.Invoke(error);
        }

        return process.ExitCode;
    }

    public static int Start(string file)
    {
        var process = Process.Start(new ProcessStartInfo
        {
            FileName = "Start.exe",
            Arguments = file,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true
        });

        process?.WaitForExit();

        return process?.ExitCode ?? -1;
    }
}
